﻿using System;

using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    public partial class Form20 : Form
    {
        public Form20()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;//禁用此异常
        }
        private Thread t1= null;
        private Thread t2= null;

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        ///  打开线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            t1 = new Thread(new ThreadStart(t1Show));
            t2=new Thread(new ThreadStart(t2Show));
            t1.Start();
            t2.Start();
            button1.Enabled= false;
            button2.Enabled= true;
        }

        /// <summary>
        /// 展示线程制造的字符
        /// </summary>
        /// <param name="ch"></param>
        private void ShowChar(char ch)
        {
            lock (this) {
                this.richTextBox1.Text += ch;
            }
        }

        /// <summary>
        /// 线程体 
        /// </summary>
        private void t1Show() {
            while (true)
            {
                ShowChar('a');
                Thread.Sleep(60);
            }
        }

        /// <summary>
        /// 线程体
        /// </summary>
        private void t2Show() {
            while (true) {
                ShowChar('A');
                Thread.Sleep(30);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
             t1.Abort();
            t2.Abort();
            button1.Enabled = true;
            button2.Enabled = false;
        }

        /// <summary>
        /// 一次性关闭使用线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private void Form20_FormLColsing(object sender, EventArgs eventArgs) { 
                if(t1!=null) t1.Abort();
                if(t2!=null) t2.Abort();
        }
    }
}
